<?php

namespace App\Http\Controllers\V1;

use Throwable;
use App\Support\Code;
use App\Support\Config;
use App\Models\Exchange;
use App\Support\Currency;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Jobs\IndirectRelease;
use Illuminate\Support\Facades\DB;
use App\Models\ConfigUserLevel;
use App\Models\ConfigDynamicRelease;
use App\Models\Packet;

class RepeatController extends ApiController
{
    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ConfigNotSetException
     */
    public function index()
    {
        $user = $this->getUser();
        return $this->success([
            'vrts' => $user->vrts,
            'VRTS_VRT' => $this->getExchangeValue()
        ]);
    }

    /**
     * 创建复投
     *
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ConfigNotSetException
     */
    public function store(Request $request)
    {
        $input = Arr::only($request->all(), ['from_value', 'to_value']);

        $user = $this->getUser();

        $input['to_currency'] = Currency::VRT;
        $input['from_currency'] = Currency::VRTS;

        $value = $user->{Currency::getStrByCode($input['from_currency'])};

        if (abs($input['from_value']) > $value) {
            return $this->fail(Code::PARAMETER_ERROR, '兑换金额不足');
        }

        $exchangeValue = (string) $this->getExchangeValue();
        $data = [
            'from_value' => big_number(abs($input['from_value'])),
        ];
        $data['to_value'] = (clone $data['from_value'])->multiply($exchangeValue);

        $function = function () use ($input, $data) {
            $user = $this->getUser();
            $exchange = Exchange::create([
                'user_id' => $user->id,
                'to_value' => $data['to_value'],
                'to_currency' => $input['to_currency'],
                'from_currency' => $input['from_currency'],
                'from_value' => $data['from_value']->negate()
            ]);

            $from = [
                'user_id' => $user->id,
                'value' => $exchange->from_value,
                'currency' => $exchange->from_currency,
                'type' => '复投至 ' . Str::upper(Currency::getStrByCode($exchange->to_currency)),
            ];

            $to = [
                'user_id' => $user->id,
                'value' => $exchange->to_value,
                'currency' => $exchange->to_currency,
                'type' => Str::upper(Currency::getStrByCode($exchange->from_currency)) . ' 复投至',
            ];

            $exchange->records()->create($to);
            $exchange->records()->create($from);
            $user->addDoubleVrt($data['to_value']);
            dispatch(new IndirectRelease($user, $exchange->to_value));
        };

        config(['api.globals.is_indirect' => true]);
        try {
            DB::transaction($function);
        } catch (Throwable $exception) {
            return $this->fail(Code::SERVER_ERROR, '复投失败');
        }

        return $this->setMsg('复投成功')->success();
    }

    /**
     * 获取复投比例
     *
     * @return mixed
     * @throws \App\Exceptions\ConfigNotSetException
     */
    private function getExchangeValue()
    {
        $config = Config::getThrow();
        $count = Exchange::whereFromCurrency(Currency::VRTS)
            ->whereToCurrency(Currency::VRT)->count();
        if ($count) {
            $value = $config['throw_second'];
        } else {
            $value = $config['throw_first'];
        }
        return $value;
    }
}
